package cvi.com.reader.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import cvi.com.reader.R;
import cvi.com.reader.base.BaseActivity;
import cvi.com.reader.bean.PartBranchBean;
import cvi.com.reader.bean.RegisterQuestionBean;
import cvi.com.reader.bean.constant;
import cvi.com.reader.network.DefaultObserver;
import cvi.com.reader.network.NetWorkManager;
import cvi.com.reader.tool.UtilsOnclickListen;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by 梅涛 on 2020/11/16.
 */

public class RegisterActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.back)
    LinearLayout back;
    @BindView(R.id.tittle)
    TextView tittle;
    @BindView(R.id.right_icon)
    LinearLayout rightIcon;
    @BindView(R.id.party_branch)
    EditText partyBranch;
    @BindView(R.id.name)
    EditText name;
    @BindView(R.id.account)
    EditText account;
    @BindView(R.id.password)
    EditText password;
    @BindView(R.id.re_password)
    EditText rePassword;
    /* @BindView(R.id.secret_insurance)
     EditText secretInsurance;*/
    @BindView(R.id.phone_number)
    EditText phoneNumber;
    @BindView(R.id.scrollView)
    ScrollView scrollView;
    @BindView(R.id.register)
    Button register;
    @BindView(R.id.party_branch_spinner)
    Spinner partyBranchSpinner;
    @BindView(R.id.secret_insurance_spinner)
    Spinner secretInsuranceSpinner;
    @BindView(R.id.pwd_check_box)
    CheckBox pwdCheckBox;
    @BindView(R.id.re_pwd_check_box)
    CheckBox rePwdCheckBox;
    @BindView(R.id.s_v)
    Switch sV;
    @BindView(R.id.party_branch_spinner1)
    Spinner partyBranchSpinner1;
    @BindView(R.id.secret_insurance_answer)
    EditText secretInsuranceAnswer;
    private int questionId;
    private String isParty = "1";
    private List<PartBranchBean.DataBean> partDataBeanList = new ArrayList<>();
    private List<String> dataPartBeanListName = new ArrayList<>();
    private List<String> dataCompanyBeanListName = new ArrayList<>();
    private ArrayAdapter<String> adapter = null;
    private ArrayAdapter<String> adapter1 = null;

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.register:
                if (UtilsOnclickListen.isFastClick()) {
                    if (!password.getText().toString().trim().equals(rePassword.getText().toString().trim())) {
                        Toast.makeText(RegisterActivity.this, "两次输入的密码不一致！", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (name.getText().toString().trim().length() < 2) {
                        Toast.makeText(RegisterActivity.this, "姓名至少为两个字！", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (account.getText().toString().trim().length() < 6) {
                        Toast.makeText(RegisterActivity.this, "账户长度至少是六位！", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (password.getText().toString().trim().length() < 6) {
                        Toast.makeText(RegisterActivity.this, "密码长度至少是六位！", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    if (contentIsEmpty()) {
                        Toast.makeText(RegisterActivity.this, "选项不能为空,请仔细检查所填项！", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    setRegister();
                }
                break;
            case R.id.back:
                finish();
                break;
        }

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_register;
    }

    @Override
    protected void initView() {
        tittle.setText("用户注册");
        back.setOnClickListener(this);
        register.setOnClickListener(this);
        rePwdCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    rePassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());//选中CheckBox，显示密码
                } else {
                    rePassword.setTransformationMethod(PasswordTransformationMethod.getInstance());//隐藏密码
                }

            }
        });
        pwdCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());//选中CheckBox，显示密码
                } else {
                    password.setTransformationMethod(PasswordTransformationMethod.getInstance());//隐藏密码
                }

            }
        });

        sV.setChecked(true);
        sV.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    isParty = "1";
                    setData(partDataBeanList, "1");

                } else {
                    isParty = "0";
                    setData(partDataBeanList, "0");
                }
                Log.d("vfaqvfv", isParty);
                //控制开关字体颜色

            }
        });
    }

    @Override
    protected void initData() {
        //密码问题接口
        NetWorkManager.getInstance().getNetWorkApiService().getRegisterQuestion().compose(this.<JSONObject>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<JSONObject>(RegisterActivity.this) {
                    @Override
                    protected void onSuccess(JSONObject response) {
                        if (response != null) {
                            setQuestion(response);
                        }


                    }
                });

        getPartData();
    }

    private void getPartData() {
        //党支部接口
        NetWorkManager.getInstance().getNetWorkApiService().getPartBranch().compose(this.<JSONObject>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<JSONObject>(RegisterActivity.this) {
                    @Override
                    protected void onSuccess(JSONObject response) {
                        if (response != null) {
                            setPartyBranch(response);
                        }

                    }
                });
    }

    //密保问题列表数据
    private void setQuestion(JSONObject response) {
        RegisterQuestionBean registerQuestionBean = response.toJavaObject(RegisterQuestionBean.class);
        List<RegisterQuestionBean.DataBean> dataBeanList = registerQuestionBean.getData();
        if (0 == dataBeanList.size()) {
            secretInsuranceSpinner.setVisibility(View.GONE);
        } else {
            secretInsuranceSpinner.setVisibility(View.VISIBLE);
            questionId = dataBeanList.get(0).getId();
        }
        List<String> strings = new ArrayList<>();
        for (int i = 0; i < dataBeanList.size(); i++) {
            strings.add(dataBeanList.get(i).getQuestion());
        }

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, strings);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//绑定 Adapter到控件
        secretInsuranceSpinner.setAdapter(adapter);
        secretInsuranceSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int pos, long id) {

                TextView textView = (TextView) view;
                textView.setTextColor(Color.parseColor("#737373"));
                textView.setTextSize(14f);
                for (int i = 0; i < dataBeanList.size(); i++) {
                    if (dataBeanList.get(i).getQuestion().equals(parent.getAdapter().getItem(pos))) {
                        questionId = dataBeanList.get(i).getId();
                    }

                }


            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // Another interface callback
            }
        });

    }

    //党支部列表数据
    private void setPartyBranch(JSONObject response) {
        PartBranchBean partBranchBean = response.toJavaObject(PartBranchBean.class);
        partDataBeanList = partBranchBean.getData();
        for (int i = 0; i < partDataBeanList.size(); i++) {

            if ("1".equals(String.valueOf(partDataBeanList.get(i).getType()))) {
                dataPartBeanListName.add(partDataBeanList.get(i).getName());
            } else if ("0".equals(String.valueOf(partDataBeanList.get(i).getType()))) {

                dataCompanyBeanListName.add(partDataBeanList.get(i).getName());
            }

        }
        partyBranchSpinner1.setVisibility(View.GONE);
        partyBranchSpinner.setVisibility(View.VISIBLE);
        if (0 == dataPartBeanListName.size()) {
            partyBranchSpinner.setVisibility(View.GONE);
        } else {
            partyBranchSpinner.setVisibility(View.VISIBLE);
        }
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, dataPartBeanListName);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//绑定 Adapter到控件
        partyBranchSpinner.setAdapter(adapter);
        adapter.notifyDataSetChanged();

        partyBranchSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int pos, long id) {

                partyBranch.setText(parent.getAdapter().getItem(pos).toString());

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // Another interface callback
            }
        });


        adapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, dataCompanyBeanListName);
        adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//绑定 Adapter到控件
        partyBranchSpinner1.setAdapter(adapter1);
        adapter1.notifyDataSetChanged();

        partyBranchSpinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int pos, long id) {

                partyBranch.setText(parent.getAdapter().getItem(pos).toString());

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // Another interface callback
            }
        });
    }

    private void setData(List<PartBranchBean.DataBean> partDataBeanList, String flag) {

        if (adapter == null) {
            return;
        }

        if ("1".equals(flag)) {
            partyBranchSpinner1.setVisibility(View.GONE);
            partyBranchSpinner.setVisibility(View.VISIBLE);
            if (dataPartBeanListName.size() > 0) {
                partyBranchSpinner.setVisibility(View.VISIBLE);
                partyBranch.setText(dataPartBeanListName.get(0));
            } else {
                partyBranchSpinner.setVisibility(View.GONE);
                partyBranch.setText("");
                partyBranch.setHint("请输入支部名称/公司名字");
            }

        } else {
            partyBranchSpinner.setVisibility(View.GONE);
            partyBranchSpinner1.setVisibility(View.VISIBLE);
            if (dataCompanyBeanListName.size() > 0) {
                partyBranchSpinner1.setVisibility(View.VISIBLE);
                partyBranch.setText(dataCompanyBeanListName.get(0));
                Log.d("asddd444", partyBranch.getText().toString() + "===" + dataCompanyBeanListName.get(0) + "flag=" + flag);
            } else {
                partyBranchSpinner1.setVisibility(View.GONE);
                partyBranch.setText("");
                partyBranch.setHint("请输入支部名称/公司名字");
            }
        }
        adapter.notifyDataSetChanged();
        adapter1.notifyDataSetChanged();
    }

    @Override
    protected void extrasDoSome(Bundle extras) {

    }

    private boolean contentIsEmpty() {
        if (partyBranch.getText().toString().trim().isEmpty() || name.getText().toString().trim().isEmpty() || account.getText().toString().trim().isEmpty()
                || password.getText().toString().trim().isEmpty() || rePassword.getText().toString().trim().isEmpty()
                || secretInsuranceAnswer.getText().toString().trim().isEmpty()) {
            return true;
        } else {
            return false;
        }
    }

    private void setRegister() {
        Map<String, Object> map = new HashMap<>();
        map.put("party_branch", partyBranch.getText().toString().trim());
        map.put("name", name.getText().toString().trim());
        map.put("account", account.getText().toString().trim());
        map.put("password", password.getText().toString().trim());

        if (!phoneNumber.getText().toString().trim().isEmpty()) {
            map.put("mobile", phoneNumber.getText().toString().trim());
            if (phoneNumber.getText().toString().trim().length() < 11) {
                Toast.makeText(RegisterActivity.this, "手机号长度至少是11位！", Toast.LENGTH_SHORT).show();
                return;
            }
        }
        map.put("secret_guard_id", questionId);
        map.put("secret_guard_answer", secretInsuranceAnswer.getText().toString().trim());
        map.put("is_party_member", isParty);
        NetWorkManager.getInstance().getNetWorkApiService().register(map).compose(this.<JSONObject>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<JSONObject>(RegisterActivity.this) {
                    @Override
                    protected void onFail(JSONObject response) {
                        super.onFail(response);
                        if (response != null) {

                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }

                    @Override
                    protected void onSuccess(JSONObject response) {
                        Toast.makeText(RegisterActivity.this, "注册成功！", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent();
                        intent.setAction(constant.CLOSElOGIN_MYRECEIVER);
                        sendBroadcast(intent);
                        jump(LoginActivity.class);
                        finish();
                    }
                });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
